package com.xzzz.irda.guardcat.server.metric.thread;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.xzzz.common.base.util.DateUtils;
import com.xzzz.common.base.util.json.JsonUtil;
import com.xzzz.common.base.util.okhttp.HttpUtil;
import com.xzzz.irda.guardcat.core.constants.GuardcatConstant;
import com.xzzz.irda.guardcat.server.app.pojo.MachineInfo;
import com.xzzz.irda.guardcat.server.metric.MetricFetchJob;
import com.xzzz.irda.guardcat.server.metric.MetricRepository;
import com.xzzz.irda.guardcat.server.metric.Repository;
import com.xzzz.irda.guardcat.server.repos.mysql.ThreadRepositoryInMySQL;
import lombok.extern.slf4j.Slf4j;

/**
 * 拉取GC指标线程
 *
 * @author xzzz
 */
@Slf4j
@Repository(repo = ThreadRepositoryInMySQL.class)
public class ThreadFetchJob extends MetricFetchJob<ThreadInfo> {

    public ThreadFetchJob(MachineInfo machineInfo, MetricRepository<ThreadInfo> metricRepository) {
        super(machineInfo, metricRepository);
    }

    @Override
    public void run() {
        String url;
        long start = System.currentTimeMillis();
        String body = null;

        try {
            url = buildUrl(GuardcatConstant.API.METRIC_SIMPLE_THREAD_INFO);
            body = HttpUtil.get(url);
        } catch (Exception e) {
            long end = System.currentTimeMillis() - start;
            log.error("[GUARDCAT] 从客户端拉取 JVM_THREAD ({}.{}.{}) 失败: {}, 用时:{}",
                    this.machine.getAppName(),
                    this.machine.getMachineId(),
                    this.machine.getIp(),
                    e.getMessage(),
                    end);
        }

        if (StrUtil.isNotBlank(body)) {
            JsonNode jsonNode = JsonUtil.toJsonNode(body);
            try {
                ThreadInfo threadInfo = toInfo(jsonNode);
                this.saveAndPublish(threadInfo);
            } catch (Exception e) {
                log.error("[GUARDCAT] 持久化 JVM_THREAD 信息异常: {}", e.getMessage());
            }
        }

    }

    /**
     * 获取 GC 信息
     *
     * @param node gc信息
     */
    private ThreadInfo toInfo(JsonNode node) {
        ThreadInfo thread = new ThreadInfo();
        if (node != null) {
            thread.setThreadCount(node.get("threadCount").asInt());
            thread.setTotalStartedThreadCount(node.get("totalStartedThreadCount").asLong());
            thread.setDaemonThreadCount(node.get("daemonThreadCount").asInt());
            thread.setPeakThreadCount(node.get("peakThreadCount").asInt());
            thread.setCreTime(DateUtils.parse(node.get("creTime").asText(), DatePattern.NORM_DATETIME_PATTERN));
        }
        return thread;
    }
}
